

//
//  CPApp.swift
//  ComponentUtils
//
//  Created by wrs on 2018/7/18.
//  Copyright © 2018年 wrs. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit
import UserNotifications
import CoreBluetooth
import Photos

// MARK: - Constant
// 当前系统版本
public let APP_VERSION = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
public let APP_BUILD = Bundle.main.infoDictionary?["CFBundleVersion"] as! String
public let APP_NAME = Bundle.main.infoDictionary?["CFBundleDisplayName"] as! String

// 屏幕宽度
public let SCREEN_HEIGHT = UIScreen.main.bounds.height

// 屏幕高度
public let SCREEN_WIDTH = UIScreen.main.bounds.width

public let SCREEN_MODE_WIDTH = UIScreen.main.currentMode?.size.width
public let SCREEN_MODE_HEIGHT = UIScreen.main.currentMode?.size.height

public let USER_DEFAULTS = UserDefaults.standard

// 通知中心
public let NOTIFICATION_CEMTER = NotificationCenter.default

public let MAIN_BUNDLE = Bundle.main

public let SHARE_APPLICATION = UIApplication.shared

public let APPDELEGATE = SHARE_APPLICATION.delegate


// MARK: - Func
public func isIpad() -> Bool {
    switch UIDevice.current.userInterfaceIdiom {
    case .pad:
        return true
    default:
        return false
    }
}

public func isIphoneXOrXS() -> Bool {
    if SCREEN_MODE_WIDTH == 1125 && SCREEN_MODE_HEIGHT == 2436 {
        return true
    } else {
        return false
    }
}

public func isIphoneXR() -> Bool {
    if SCREEN_MODE_WIDTH == 828 && SCREEN_MODE_HEIGHT == 1792 {
        return true
    } else {
        return false
    }
}

public func isIphoneXSMax() -> Bool {
    if SCREEN_MODE_WIDTH == 1242 && SCREEN_MODE_HEIGHT == 2688{
        return true
    } else {
        return false
    }
}

public func isIphoneXOrLater() -> Bool {
    if isIphoneXOrXS() || isIphoneXR() || isIphoneXSMax() {
        return true
    } else {
        return false
    }
}

public func getKeyWindow() -> UIWindow? {
    var window = UIApplication.shared.keyWindow
    if #available(iOS 13, *) {
        var mainWindow: UIWindow? = nil
       let windows = UIApplication.shared.windows
       for w in windows {
            if w.isKeyWindow {
                mainWindow = w
                break
            }
        }
        if mainWindow == nil {
          mainWindow = UIApplication.shared.windows.first
        }
        if let w = mainWindow {
            window = w
        }
    }
    return window
}

public func getStatusBarHeight() -> CGFloat {
    var height: CGFloat = 44
    if #available(iOS 13, *) {
        if let h = getKeyWindow()?.windowScene?.statusBarManager?.statusBarFrame.size.height {
            height = h
        }
    } else {
      height =  UIApplication.shared.statusBarFrame.size.height
    }
    return height
//    if isIphoneXOrLater() {
//        return CGFloat(44.0)
//    } else {
//        return CGFloat(20)
//    }
}

public func getNavigationBarHeight() -> CGFloat {
    return CGFloat(44.0)
}


// tabbar + safeArea 高度
public func getTabBarHeight() -> CGFloat {
    if isIphoneXOrLater() {
       return CGFloat(83.0)
    } else {
         return CGFloat(49.0)
    }
}

public func getSafeAreaBottomHeight() -> CGFloat {
    if isIphoneXOrLater() {
        return CGFloat(44.0)
    } else {
        return CGFloat(0.0)
    }
}

public func getUserDefaultValue(key: String) -> AnyObject? {
    let value: AnyObject = USER_DEFAULTS.value(forKey: key) as AnyObject
    return value
}

public func setUserDefaultValue(key: String, value: AnyObject) {
    USER_DEFAULTS.setValue(value, forKey: key)
    USER_DEFAULTS.synchronize()
}

//根据键盘监控  获取键盘高度
public func getKeyBoardHeight(not: Notification) -> CGFloat{
    let avalue = not.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
    let keyrect : CGRect = avalue.cgRectValue
    let keyheight : CGFloat = keyrect.size.height;
    return keyheight
}

public func getKeyBoardAnimationTime(not: Notification) -> Float{
    let value = not.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber
    return value.floatValue
}

public func getAppVersionString() -> String {
    var value = ""
    if let str =  Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String{
        value = str
    }
   return value
}

// MARK: - OPEN
public enum SettingPageType: String {
    case App = "app"
    case Bluetooth = "Bluetooth"
}

public func openSetting(type: SettingPageType) {
    switch type {
    case .App:
        openAppSetting()
    case .Bluetooth:
      
//        let str = UIApplication.
//        openURL(url: str)
        break;
//    default:
//        let url = type.rawValue
//        openURL(url: url)
    }
}

public func openURL(url: String) {
    if let urlValue = URL(string: url) {
        openURL(url: urlValue)
    }
}

public func openURL(url: URL) {
    if UIApplication.shared.canOpenURL(url) {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:]) { (suc: Bool) in
            
            }
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}

public func openAppSetting() {
    let str = UIApplication.openSettingsURLString

    openURL(url: str)
}

public func openGrade(appleID: String) {
    openURL(url: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appleID)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8")
}

public func openStoreHomePage(appleID: String) {
      openURL(url: "https://itunes.apple.com/cn/app/id\(appleID)?mt=8")
}

public func openEmail(email: String) {
    openURL(url: "mailto://\(email)")
}

public func openTel(tel: String) {
    openURL(url: "tel://\(tel)")
}

public func openSMS(sms: String) {
    openURL(url: "sms://\(sms)")
}

public func openRemote(remote: String) {
    openURL(url: "remote://\(remote)")
}

public func openSysMapApp(address: String, handle:@escaping ((_ suc: Bool, _ aError: Error?)->Void)) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { ( placemarks, error) in
        if let err = error {
            handle(false, err)
        } else {
            if let array = placemarks {
                if array.count > 0 {
                    var tempArray = [MKMapItem]()
                    for mark in array {
                        let coordinate = CLLocationCoordinate2DMake(mark.location!.altitude, mark.location!.coordinate.longitude)
                        let toMark: MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
                        let toLocation = MKMapItem(placemark: toMark)
                        toLocation.name = mark.name
                        tempArray.append(toLocation)
                    }
                    MKMapItem.openMaps(with: tempArray, launchOptions: nil)
                } else {
                    handle(false, nil)
                }
            } else {
                 handle(false, nil)
            }
        }
    }
}

// MARK: - 权限
public func getVideoAuthorization(_ handle: @escaping (_ author: Bool) -> Void) -> Void  {
    let status  = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    switch status {
    case .authorized:
        handle(true)
    case .notDetermined:
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (flag) in
            handle(flag)
        }
    default:
       handle(false)
    }
}

public func getPhotoLibraryAuthorization(_ handle: @escaping (_ author: Bool) -> Void) -> Void {
    PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .authorized:
             handle(true)
            break
        default:
              handle(false)
            break
        }
    }
}

public func getNotificationAuthorization(_ handle: @escaping (_ author: Bool) -> Void) -> Void {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings { (setting) in
            switch setting.authorizationStatus {
                case .authorized:
                    handle(true)
                // 没有监测到时应到请求通知权限后再回调
                case .notDetermined:
                    handle(false)
                default:
                    handle(false)
            }
        }
    } else {
        if let types = UIApplication.shared.currentUserNotificationSettings?.types {
            if types == UIUserNotificationType.alert || types == UIUserNotificationType.sound || types == UIUserNotificationType.badge {
               handle(true)
            } else {
                handle(false)
            }
        } else {
            handle(false)
        }
    }
}

public func getBluetoothAuthorization(_ handle: @escaping (_ author: Bool) -> Void) ->Void {
   let status = CBPeripheralManager.authorizationStatus()
    switch status {
    case .authorized:
        handle(true)
     // 没有监测到时应到请求蓝牙权限后再回调
    case .notDetermined:
        handle(false)
    default:
        handle(false)
    }
}

public func getLocationAuthorization() -> Bool {
   let serversEnabled =  CLLocationManager.locationServicesEnabled()
    if serversEnabled { // 是否打开了位置服务
        let authorizationStatus = CLLocationManager.authorizationStatus()
        switch authorizationStatus {
        case .authorizedAlways:
            return true
        case .authorizedWhenInUse:
            return true
        default:
            return false
        }
    } else {
        return false
    }
   
}

// MARK: -
public func DLOG<T>(message: T)
{
   DPrint(message: message)
}

public func DPrint<T>(message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line)
{
    #if DEBUG
    // 要把路径最后的字符串截取出来
    let fName = ((fileName as NSString).pathComponents.last!)
    print("\(fName).\(methodName)[\(lineNumber)]: \(message)")
    #endif
}

public func adjustScrollViewInsets(scrollView: UIScrollView, vc: UIViewController) -> Void {
    if #available(iOS 11.0, *) {
         scrollView.contentInsetAdjustmentBehavior = .never
    } else {
        vc.automaticallyAdjustsScrollViewInsets = false
    }
}

public func adjustTableViewExtimatedZero(tableView: UITableView) -> Void {
    tableView.estimatedSectionFooterHeight = 0
    tableView.estimatedSectionHeaderHeight = 0
}


func getCurrentViewController() -> UIViewController? {
    var currentVC: UIViewController?
    let rootVC: UIViewController? = getKeyWindow()?.rootViewController
    if let tabbarVC = rootVC as? UITabBarController {
        currentVC = getTabbarTopVC(tabbarVC: tabbarVC)
    } else if let navVC = rootVC as? UINavigationController {
        currentVC = getNavTopVC(navVC: navVC)
    } else {
        currentVC = rootVC
    }
    if let presentedVC = currentVC?.presentedViewController {
        if let tabbarVC = presentedVC as? UITabBarController {
            currentVC = getTabbarTopVC(tabbarVC: tabbarVC)
        } else if let navVC = presentedVC as? UINavigationController {
            currentVC = getNavTopVC(navVC: navVC)
        } else {
            currentVC = presentedVC
        }
    }
    return currentVC
}

func getTabbarTopVC(tabbarVC: UITabBarController) -> UIViewController {
    var currentVC: UIViewController = tabbarVC
    let selectedVC = tabbarVC.selectedViewController
    if let navVC = selectedVC as? UINavigationController {
        currentVC = getNavTopVC(navVC: navVC)
    } else if let tempTabbbarVC = selectedVC as? UITabBarController{
        currentVC = getTabbarTopVC(tabbarVC: tempTabbbarVC)
    }
    return currentVC
}

func getNavTopVC(navVC: UINavigationController) -> UIViewController {
    var currentVC: UIViewController = navVC
    if let topVC = navVC.topViewController {
        currentVC = topVC
    }
    return currentVC
}


func isSimulator() -> Bool {
    var isSim = false
#if arch(i386) || arch(x86_64)
    isSim = true
#endif
    return isSim
}

